import * as React from 'react'
import ReactDOM from 'react-dom'
import canUseDom from './dom/canUseDom'

export interface PortalProps {
  didUpdate?: (prevProps: PortalProps) => void
  getContainer: () => HTMLElement
  children?: React.ReactNode
}

const Portal = React.forwardRef<any, PortalProps>((props, ref) => {
  const { didUpdate, getContainer, children } = props

  const containerRef = React.useRef<any>()

  React.useImperativeHandle(ref, () => { })

  const initRef = React.useRef(false)

  if (!initRef.current && canUseDom()) {
    containerRef.current = getContainer()
    initRef.current = true
  }

  React.useEffect(() => {
    didUpdate?.(props)
  })

  React.useEffect(() => {
    return () => {
      containerRef.current?.parentNode?.removeChild(containerRef.current);
    }
  }, [])

  return containerRef.current
    ? ReactDOM.createPortal(children, containerRef.current) : null

})
